<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Services;

use App\Libs\Email\EmailImap;
use App\Models\Blog\Lists;
use App\Models\Common\Category;
use App\Models\Expansion\EmailReceive;
use App\Models\System\EmailHair;
use App\Models\System\File;
use App\Models\System\Permission;
use Carbon\Carbon;

class CommonService
{

    use Service;

    /**
     * 文件树
     *
     * @param string      $name
     * @param string|NULL $static
     * @param string|NULL $title
     * @param bool        $tree
     * @param array       $dis
     *
     * @return array|string
     */
    public function TreeChildService( string $name, string $static = NULL, string $title = NULL, bool $tree = FALSE, array $dis = [] )
    {
        $disk     = $this->getStorage($static);
        $category = [];
        $cate     = [];
        $nameFile = [];
        $public   = $disk->directories($name);//获取目录下得所有子目录
        foreach ( $public as $key => $value ) {
            if ( $name ) $names = explode($name . '/', $value);
            else $names = explode('/', $value);
            $nameInfo = explode('/', $names[ count($names) - 1 ]);
            if ( in_array(reset($nameInfo), $category) ) continue;//如果存在就跳出 否则就赋值
            $category[] = reset($nameInfo);
            $cate[]     = $value;
            unset($names);
        }
        $true = explode('/', $title);
        foreach ( $category as $key => $value ) {
            if ( in_array($value, $dis) ) continue;
            $nameFile[ $key ][ 'name' ] = $value;
            if ( ! $tree ) $nameFile[ $key ][ 'title3' ] = '&#xe640;';//这里给树添加样式
            $nameFile[ $key ][ 'id' ] = $cate[ $key ];
            if ( in_array($nameFile[ $key ][ 'name' ], $true) ) $nameFile[ $key ][ 'spread' ] = TRUE;//是否展开树
            else $nameFile[ $key ][ 'spread' ] = FALSE;
            $nameFile[ $key ][ 'children' ] = $this->TreeChildService($cate[ $key ], $static, $title, $tree);//树
            if ( ! $nameFile[ $key ][ 'children' ] ) unset($nameFile[ $key ][ 'children' ]);
        }
        return $nameFile;
    }

    /**
     * 获取邮件
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function emailLaZaRd()
    {
        $disk = $this->getStorage();
        $path = 'email';
        $disk->makeDirectory($path);//创建文件夹
        $email = EmailHair::FindModel([ 'username', 'password', 'server', 'port' ]);//查询配置
        File::ForceDeleteModel([ 'uid' => 0 ]);//删除数据库里得邮件
        EmailReceive::TruncateModel();//清空邮件表
        $disk->deleteDirectory('admin/0');//删除邮件附件
        $time = Carbon::now();
        $user = $email->username ? : env('MAIL_USERNAME');
        $pass = $email->password ? : env('MAIL_PASSWORD');
        $host = $email->server ? : env('MAIL_HOST');
        $port = $email->port ? : env('MAIL_PORT');
        set_time_limit(0);
        $mail    = new EmailImap();
        $connect = $mail->mailConnect($user, $pass, $host, $port);
        if ( ! $connect ) return message($this->getErrorCode()::message(1012));

        $totalCount = $mail->mailTotalCount();//邮件总数
        $category   = 'email-imap';
        $user       = 'admin';
        $id         = 0;
        for ( $i = $totalCount; $i > 0; $i-- ) {
            $disk->makeDirectory("$user/$id/$category");
            $file           = $mail->getAttach($i, "$user/$id/$category/");//获取邮件附件保存并返回文件名
            $mailHeader     = $mail->mailHeader($i);//获取邮件标题
            $body           = $mail->getBody($i);//获取邮件正文
            $data[ 'file' ] = '';
            foreach ( $file as $value ) {
                if ( empty($value) ) continue;
                $ext                   = pathinfo($value, PATHINFO_EXTENSION);
                $url                   = $disk->url($user . '/' . $id . '/' . $category . '/' . $ext . '/' . $value);//文件url
                $file_url              = $disk->fileUrl($user . '/' . $id . '/' . $category . '/' . $ext . '/' . $value);//详细路径
                $data1[ 'ext' ]        = $ext;
                $data1[ 'uid' ]        = $id;
                $data1[ 'category' ]   = $category;
                $data1[ 'name' ]       = $value;
                $data1[ 'filename' ]   = $value;
                $data1[ 'url' ]        = $url;
                $data1[ 'file_url' ]   = $file_url;
                $data1[ 'hash' ]       = hash_file('sha256', $url);//文件哈希
                $data1[ 'user' ]       = $user;
                $data1[ 'size' ]       = maxsize($disk->size($user . '/' . $id . '/' . $category . '/' . $ext . '/' . $value));//计算文件大小
                $data1[ 'created_at' ] = $time;
                $data1[ 'updated_at' ] = $time;
                $data[ 'file' ]        .= File::InsertGetIdModel($data1) . ',';//存入文件表，多个文件，隔开
            }
            if ( $mailHeader == [] ) {
                $data[ 'sender' ] = '无';
                $data[ 'name' ]   = '无';
                $data[ 'title' ]  = '无';
                $data[ 'status' ] = 2;
                $data[ 'eid' ]    = 0;
            }
            else {
                $data[ 'sender' ] = $mailHeader[ 'from' ];
                $data[ 'name' ]   = $mailHeader[ 'fromName' ];
                $data[ 'title' ]  = $mailHeader[ 'subject' ];
                $data[ 'status' ] = $mailHeader == 'U' ? 1 : 2;
                $data[ 'eid' ]    = $mailHeader[ 'id' ];
                $date             = Carbon::create(1999, 1, 1);
                $time             = date("Y-m-d H:i:s", strtotime($mailHeader[ 'date' ]));
                if ( $date->gt($time) ) $data[ 'created_at' ] = Carbon::now();
                else $data[ 'created_at' ] = $time;
            }
            $email = EmailReceive::CreateModel($data);//入库
            $disk->put($path . '/email-' . $email->id . '.html', $body);//邮件内容写入html文件
            $success[ 'name' ]   = $data[ 'name' ];
            $success[ 'time' ]   = Carbon::now();
            $success[ 'title' ]  = $data[ 'title' ];
            $success[ 'sender' ] = $data[ 'sender' ];
            errorStorage('email', $success, '自动写入数据库', 'success', '自动写入数据库');
        }
        $mail->closeMail();
        return data();
    }

    /**
     * 排序
     *
     * @param        $array     数据
     * @param string $db        模型
     * @param int    $parent_id 父级
     * @param int    $level     层级
     * @param int    $id        当前层次
     *
     * @return bool
     */
    public function sort( $array, $db = 'permission', $parent_id = 0, $level = 3, $id = 1 )
    {
        if ( $level == $id ) return message();
        if ( ! empty($array) ) {
            foreach ( $array as $key => $value ) {
                if ( is_array($array) ) {
                    if ( $parent_id !== FALSE ) $data[ 'parent_id' ] = $parent_id;
                    $data[ 'sort_order' ] = $key + 1;
                    switch ( $db ) {
                        case 'permission':
                            Permission::UpdateModel([ 'id' => $value[ 'id' ] ], $data);
                            break;
                        case 'category':
                            Category::UpdateModel([ 'id' => $value[ 'id' ] ], $data);
                            break;
                        case 'list':
                            Lists::UpdateModel([ 'id' => $value[ 'id' ] ], $data);
                            break;
                        default:
                            return message();
                            break;
                    }
                    $id++;
                    if ( isset($value[ 'children' ]) && $value[ 'children' ] ) $this->sort($value[ 'children' ], $db, $value[ 'id' ], $level, $id);
                }
            }
        }
        return TRUE;
    }
}
